package com.example.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.controller.InsuredPersonController;
import com.example.entity.User;
import com.example.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.security.EncryptionService;
import com.example.security.JwtTokenProvider;

import java.util.List;
import java.util.Objects;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private EncryptionService encryptionService;

    @Autowired
    private JwtTokenProvider jwtTokenProvider;
    
    @Autowired
    private InsuredPersonController insuredPersonController;

    // 用户注册（默认加密密码）
    public void register(User user) {
        String encryptedPassword = encryptionService.encryptPassword(user.getPassword());
        user.setPassword(encryptedPassword);  // 加密用户密码
        user.setRole("InsuredPerson");  // 设置默认角色为参保人员
        userMapper.insert(user);
        insuredPersonController.registerInsuredPerson(Integer.parseInt(user.username));
    }

    // 用户登录
    public String login(String username, String password, String role) {
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
        if (user != null && encryptionService.checkPassword(password, user.getPassword()) && Objects.equals(role, user.getRole())) {
            return jwtTokenProvider.generateToken(user.getUsername());  // 生成JWT token
        }
        throw new IllegalArgumentException("用户名或密码错误");
    }

    // 更新用户信息
    public void updateUser(User user) {
        userMapper.updateById(user);
    }

    // 更新密码
    public void updatePassword(String username, String newPassword) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        User user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            throw new IllegalArgumentException("用户未找到");
        }
        user.setPassword(encryptionService.encryptPassword(newPassword));  // 更新加密后的密码
        userMapper.updateById(user);
    }

    // 删除用户
    public void deleteUser(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        userMapper.delete(queryWrapper);
    }

    // 获取所有用户，返回 Java List
    public List<User> getAllUsers() {
        return userMapper.selectList(null);  // 直接返回 Java 的 List
    }

    // 搜索用户，返回 Java List
    public List<User> searchUsers(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("username", username);
        return userMapper.selectList(queryWrapper);  // 直接返回 Java 的 List
    }
}
